package cn.yuan.arithmetic.sort;

/**
 * 希尔排序实现.
 *
 * @author : yjs
 * @date: 2020-12-17 10:45
 */
public class ShellSort {

    public static void main(String[] args) {
        int[] array = {3, 4, 7, 4, 1, 9, 13, 24, 11, 45, 22, 45};
        System.out.println(print(array));
        ShellSort.sort(array);
        System.out.println(print(array));
    }

    /**
     * 实现
     */
    public static void sort(int[] array) {
        // 希尔排序
        int d = array.length;
        while (true) {
            d = d / 2;
            for (int x = 0; x < d; x++) {
                for (int i = x + d; i < array.length; i = i + d) {
                    int temp = array[i];
                    int j;
                    for (j = i - d; j >= 0 && array[j] > temp; j = j - d) {
                        array[j + d] = array[j];
                    }
                    array[j + d] = temp;
                }
            }
            if (d == 1) {
                break;
            }
        }
    }

    /**
     * 打印
     */
    private static String print(int[] array) {
        StringBuilder sb = new StringBuilder("[");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
            if (i < array.length - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
